<?php

namespace App\HttpController\Api\Attend\Student;

use EasySwoole\Http\Message\Status;
use App\Model\Attend\Leavelog as LeavelogModel;
use App\Model\Attend\Leave as LeaveModel;
use App\Model\Attend\LeaveAuth as LeaveAuthModel;

use App\Model\Admin\AttendGroupModel;
use App\Model\Admin\AttendClassModel;
use App\Model\Admin\AttendRuleClassRelModel;

use App\Model\Attend\Calendar as CalendarModel;

use App\Model\Admin\ClassesModel;

use App\Model\Admin\Schedule as ScheduleModel;


use App\HttpController\Api\Admin\AdminBase;
use App\Lib\Utils;
use App\Model\Admin\StudentModel;

class Leavelog extends AdminBase
{
    /**
     * 请假记录列表
     */
    public function index()
    {
        $where = [
            'scope' => 1,
            'school_code' => $this->userinfo['school_code']
        ];
        if (isset($this->params['name']) && !empty($this->params['name'])) {
            $where['name'] = ['%'.$this->params['name'].'%','like'];
        }
        if (isset($this->params['number']) && !empty($this->params['number'])) {
            $where['number'] = $this->params['number'];
        }

        try {
            $field = '`id`, `name`, `number`, `unit`, `leave_id`, `first_time`, `last_time`, `day`, `hour`, `create_time`, `status`, `source`, `remark`';
            $leaveLogObj = new LeaveLogModel();

            $data = $leaveLogObj->getPageList($field, $where, $this->params['page'], $this->params['limit']);
            $leaveObj = new LeaveModel();
            $leaveData = $leaveObj->getIDName(['scope' => 1, 'school_code' => $this->userinfo['school_code']]);

        } catch(\Exception $e) {
            echo $e->getMessage();
            return $this->errorJson("Server Error");
        }

        if (!empty($data['lists'])) {
            $statusArr = [
                -2 => '已撤销',
                -1 => '未通过',
                1 => '待审核',
                2 => '通过'
            ];

            foreach ($data['lists'] as &$list) {
                $list['leave_name'] = $leaveData[$list['leave_id']] ?? '/';
                $list['create_time'] = date('Y-m-d H:i', $list['create_time']);
                $list['first_time'] = date('Y-m-d H:i', $list['first_time']);
                $list['last_time'] = date('Y-m-d H:i', $list['last_time']);
                $list['status'] = $statusArr[$list['status']] ?? '';
                $list['start'] = date('Y-m-d H:i', $list['first_time']);
                $list['end'] = date('Y-m-d H:i', $list['last_time']);
            }
        }
        return $this->dataJson([
            'count' => $data['count'],
            'data' => $data['lists']
        ]);
    }

    /**
     * 添加请假记录
     */
    public function add()
    {
        $str = $this->raw;
        $this->params = json_decode(Utils::characet($str), true);

        $data = [];
        if (isset($this->params['name']) && !empty($this->params['name'])) {
            $data['name'] = $this->params['name'];
        } else {
            return $this->errorJson('请假人姓名有误');
        }

        if (isset($this->params['userId']) && !empty($this->params['userId'])) {
            $data['user_id'] = $this->params['userId'];
        } else {
            return $this->errorJson('请假人ID有误');
        }

        if (isset($this->params['number']) && !empty($this->params['number'])) {
            $data['number'] = $this->params['number'];
        } else {
            return $this->errorJson('请假人学号有误');
        }

        if (isset($this->params['leave_id']) && !empty($this->params['leave_id'])) {
            $data['leave_id'] = $this->params['leave_id'];
        } else {
            return $this->errorJson('请假类型有误');
        }

        if (isset($this->params['startDate']) && !empty($this->params['startDate'])) {
            $data['first_time'] = strtotime($this->params['startDate']);
        } else {
            return $this->errorJson('请假开始时间有误');
        }

        if (isset($this->params['endDate']) && !empty($this->params['endDate'])) {
            $data['last_time'] = strtotime($this->params['endDate']);
        } else {
            return $this->errorJson('请假结束时间有误');
        }

        if (isset($this->params['remark']) && !empty($this->params['remark'])) {
            $data['remark'] = $this->params['remark'];
        }

        try {
            $leaveLogObj = new LeaveLogModel();
            $leaveObj = new LeaveModel();
            $leaveName = $leaveObj->getOne('id, name', ['id' => $data['type']]);

            $leaveWhere = [];
            $leaveWhere['scope'] = 1;
            $leaveWhere['school_code'] = $this->userinfo['school_code'];

            if ($data['first_time'] == $data['last_time']) {
                $sleaveWhere = "(((first_time between {$data['first_time']} and {$data['last_time']}) or (last_time between {$data['first_time']} and {$data['last_time']})) or (({$data['first_time']} between first_time and last_time) or ({$data['last_time']} between first_time and last_time)))";
            } else {
                $sleaveWhere = "(((first_time between {$data['first_time']} and {$data['last_time']}) or (last_time between {$data['first_time']} and {$data['last_time']})) or (({$data['first_time']} between first_time and last_time) or ({$data['last_time']} between first_time and last_time)))";
            }

            $isset = $leaveLogObj->getLeaveLog('id', $leaveWhere, ['id', 'desc'], $sleaveWhere);

            if ($isset && is_array($isset)) {
                return $this->errorJson('假期已存在');
            }

            $data['scope'] = 1;
            $data['create_time'] = time();
            $data['status'] = 1; // 1 待审核
            $data['school_code'] = $this->userinfo['school_code'];
            $data['leave_name'] = $leaveName['name'];
            $data['source'] = 1; // 1 后台添加，2 手机提交
            $logid = $leaveLogObj->add($data);

        } catch(\Exception $e) {
            echo $e->getMessage();
            return $this->errorJson("Server Error");
        }
        
        if (!empty($logid)) {
            return $this->dataJson(['id' => $logid]);
        } else {
            return $this->errorJson('操作数据失败');
        }
    }

    /**
     * 获取学生编号
     */
    public function getNumbers()
    {
        if (isset($this->params['name']) && !empty($this->params['name'])) {
            $name = $this->params['name'];
        } else {
            return $this->errorJson('姓名有误');
        }
        try {
            $model = new StudentModel();
            $field = '`number`,`id`';
            $where = [];
            $where['name'] = $name;
            $where['school_code'] = $this->userinfo['school_code'];
            $where['mark'] = 1;

            $staff = $model->getAll($field, $where);
            if ($staff) {
                return $this->dataJson($staff);
            } else {
                return $this->errorJson('名字有误');
            }
        } catch(\Exception $e) {
            echo $e->getMessage();
            return $this->errorJson("Server Error");
        }
    }

    /**
     * 删除请假记录
     */
    public function delete()
    {
        if (isset($this->params['id']) && !empty($this->params['id'])) {
            $id = $this->params['id'];
        } else {
            return $this->errorJson('参数错误');
        }
        try {
            $leaveLogObj = new LeaveLogModel();
            $result = $leaveLogObj->destroy([
                'id' => $id,
                'scope' => 1,
                'school_code' => $this->userinfo['school_code']
            ]);
        } catch (\Exception $e) {
            return $this->errorJson("Server Error");
        }

        if ($result) {
            return $this->successJson('删除成功');
        } else {
            return $this->errorJson('删除失败');
        }
    }

    /**
     * 撤销申请
     */
    public function cancel()
    {
        if (isset($this->params['id']) && !empty($this->params['id'])) {
            $id = $this->params['id'];
        } else {
            return $this->errorJson('参数错误');
        }

        $where = [
            'id' => $id,
            'scope' => 1,
            'school_code' => $this->userinfo['school_code']
        ];

        try {
            $model = LeavelogModel::create()->get($where);
            if (empty($model)) {
                return $this->errorJson('记录不存在');
            }
            $result = $model->update(['status' => -2]);

        } catch (\Exception $e) {
            return $this->errorJson("Server Error");
        }

        if ($result) {
            return $this->successJson('操作成功，申请已撤销');
        } else {
            return $this->errorJson('操作失败');
        }
    }

}
